const fs = require('fs');

/**
 *
 * @param dir
 * @param callback
 */
function readFileList(dir,callback) {
  fs.readdir(dir, (err, files) => {
    new Promise((resolve,reject)=>{
      !err ? resolve() : reject(err);
    }).then(
        ()=>{
          let filesList = [];
          files.forEach((item) => {
            let fullPath = dir[dir.length - 1] === '/' ? `${dir}${item}` : `${dir}/${item}`;
            filesList.push(fullPath);
          })
          callback(null,filesList);
        }
        ,(error)=>{
          callback(error,null);
        }
    ).catch((e)=>{
      throw new Error(e);
    })
  });
}

/**
 *
 * @param {string} path
 * @param {Function} callback
 */
function readFile(path,callback){
  fs.readFile(path,callback);
}

/**
 * check path
 * @param path
 * @param callback
 */
function checkPath(path, callback) {
  /*fs.access(path, fs.constants.F_OK, (err) => {
    callback(!err);
  })*/
  fs.stat(path,(error,stats)=>{
    new Promise((resolve,reject)=>{
      !error ? resolve(stats) : reject(error);
    }).then(
        (stats)=>{
          callback(false,stats.isFile())
        }
        ,(error)=>{
          callback(error,null);
        }
    ).catch((error)=>{
      callback(error,null);
    })
  })
}

/**
 *
 * @param path
 * @param callback
 */
function readStrem(path,callback){
  fs.createReadStream(path,callback);
}

module.exports = {
  readFileList : readFileList,
  readFile : readFile,
  readStrem:readStrem,
  checkPath:checkPath
}